package encryption;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class BasicUtil {

	private static Log log = LogFactory.getLog(BasicUtil.class);

	// 接口输出参数处理
	public static String getOutMsg(String err_code, String err_msg,
			String dataList, String total_count) {
		String str = "";

		try {
			err_msg = err_msg != null ? err_msg.replaceAll("\"", "#") : "";

			// String data = dataList;
			JSONObject obj = new JSONObject();
			obj.put("flag", err_code);
			obj.put("msg", err_msg);
			obj.put("result", dataList);
			// obj.put("total_count", total_count);

			str = obj.toString();
			// log.debug("data:"+str);

		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return str;
	}

	// 把json中元素按照key值排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串数
	public static String paramSort(JSONObject jso) {
		String prestr = "";
		List<String> keys = null;
		try {
			keys = new ArrayList<String>(jso.keySet());
			Collections.sort(keys);

			for (int i = 0; i < keys.size(); i++) {
				String key = keys.get(i);
				String value = jso.get(key).toString();
				if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
					prestr = prestr + key + "=" + value;
				} else {
					prestr = prestr + key + "=" + value + "&";
				}
			}
		} catch (Exception e) {
			log.error("排序异常：" + e.getMessage());
		} finally {
			keys = null;
			Collections.emptyList();
		}

		// log.debug("argSort:" + prestr);
		return prestr;
	}


}
